package by.alex.dzeshko.facebooksuperclient.adapter;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import by.alex.dzeshko.facebooksuperclient.R;
import by.alex.dzeshko.facebooksuperclient.image.ImageLoader;
import by.alex.dzeshko.facebooksuperclient.providers.contract.FbContract;

public class FriendsListCursorAdapter extends CursorAdapter {
	
	public FriendsListCursorAdapter(Context context, Cursor c) {
		super(context, c, false);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (!mDataValid) {
			throw new IllegalStateException("this should only be called when the cursor is valid");
		}
		if (!mCursor.moveToPosition(position)) {
			throw new IllegalStateException("couldn't move cursor to position " + position);
		}
		View v;
		if (convertView == null) {
			v = newView(mContext, mCursor, parent);
			ViewHolder holder = new ViewHolder();
			holder.tvFriendName = (TextView) v.findViewById(R.id.tvFriendListName);
			holder.ivFriendPicture = (ImageView) v.findViewById(R.id.ivFriendListPicture);
			v.setTag(R.string.viewHolder, holder);
		} else {
			v = convertView;
		}
		bindView(v, mContext, mCursor);
		return v;
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {

		// checking for tag to avoid entrance headers and footers to adapter
		Object tag = view.getTag(R.string.tag);
		if(tag!=null){
			return;
		}
		ViewHolder holder = (ViewHolder) view.getTag(R.string.viewHolder);
		String name = cursor.getString(cursor.getColumnIndex(FbContract.FriendsColumns.FRIEND_NAME));
		holder.tvFriendName.setText(name);
		String url = cursor.getString(cursor.getColumnIndex(FbContract.FriendsColumns.PICTURE_URL));
		ImageLoader imLoader = ImageLoader.getInstance();
		holder.ivFriendPicture.setImageResource(R.drawable.com_facebook_profile_default_icon);
		imLoader.bind(this, holder.ivFriendPicture,url);
		
	}

	@Override
	public View newView(Context ctx, Cursor cursor, ViewGroup viewGroup) {
		View view = View.inflate(viewGroup.getContext(), R.layout.adapter_friends_list, null);
		return view;
	}

	static class ViewHolder{
		TextView tvFriendName;
		ImageView ivFriendPicture;
	}
}
